# fastapi request对象
from fastapi import FastAPI, Request
# 静态文件
from fastapi.staticfiles import StaticFiles
# tortoise_orm
from tortoise.contrib.fastapi import register_tortoise
# tortoise_orm 配置文件
from settings import TORTOISE_ORM  # 确保这里的导入是有效的
from contextlib import asynccontextmanager
# 异步运行fastapi
import uvicorn
# 解决跨域问题
from fastapi.middleware.cors import CORSMiddleware

# 待解决：1.登录注册接口  2.ts.py里面的获取图书

# 路由转发
from api.ts import api_book
from api.cbs import api_cbs
from api.zz import api_zz
from api.zz import api_zz

# 创建 lifespan 上下文管理器
@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动代码：在应用启动前执行
    # 注册 Tortoise ORM
    from tortoise.contrib.fastapi import register_tortoise
    from settings import TORTOISE_ORM
    register_tortoise(
        app,
        config=TORTOISE_ORM,
        generate_schemas=True,
        add_exception_handlers=True,
    )
    yield
    # 关闭代码：在应用关闭后执行（可选）


# 实例化fastapi创建应用时传入 lifespan 参数
app = FastAPI(lifespan=lifespan)

# 设置静态文件路由
app.mount("/uping", StaticFiles(directory="uping"), name="uping")

# 路由分发
app.include_router(api_book, prefix="/book/ts", tags=["books"])

# 创建一个根路由
@app.get("/")
async def read_root(request: Request):
    return '马嘉璐，你最棒！！！'


# 功能1-注册接口
# data 存放业务数据；meta 状态码和提示信息 -> ret 后端返回给前端的
ret = {
    "data": {},
    "meta": {
        "status": 200,
        "message": ""
    }
}

from models import Guanli

@app.post("/register")
async def register(request: Request):
    # Request 接收前端给的信息 -> 解析参数
    json_data = await request.json()
    username = json_data['username']
    password = json_data['password']
    print(username, password)

    # 数据库查询，有没有数据 -> 将数据 ret 返回给前端
    user = await Guanli.filter(username=username, password=password)
    if len(user) != 0:
        ret["data"]["username"] = username
        ret["meta"]["status"] = 500
        ret["meta"]["message"] = "当前注册"
    else:
        await Guanli.create(username=username, password=password)
        ret["data"]["username"] = username
        ret["meta"]["message"] = "注册成功"

    return ret

@app.post("/login")
async def login(request: Request):
    json_data = await request.json()
    username = json_data['username']
    password = json_data['password']
    user = await Guanli.filter(username=username, password=password).first()
    if user is not None:
        ret["data"]["username"] = username
        ret["meta"]["status"] = 200
        ret["meta"]["message"] = "登录成功"
    else:
        ret["meta"]["status"] = 500
        ret["meta"]["message"] = "用户名不存在"
    return ret

#     跨域
app.add_middleware(
    CORSMiddleware,
    # allow_origins=origins,  # *: 代表所有客户端
    allow_origins=["*"],  # *: 代表所有客户端
    allow_credentials=True,
    allow_methods=["*"], # allow_methods=["GET"] 只允许"GET"请求，如果是*表示可以是所有请求；
    allow_headers=["*"],
)

# 推荐命令行启动：uvicorn main:app --reload --host 127.0.0.1 --port 8000
# if __name__ == '__main__':
#     uvicorn.run("main:app", host='127.0.0.1', port=8000,reload=True)